package com.halfsword.creativecraft.gui.machine;

import com.halfsword.creativecraft.CreativeCraft;
import com.halfsword.creativecraft.block.BlockLoader;
import com.halfsword.creativecraft.block.custom.machine.blockentity.SteamPowerCrusherBlockEntity;
import com.halfsword.creativecraft.gui.MenuTypes;
import com.halfsword.creativecraft.modules.StagedSteamMechanism;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.*;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraftforge.common.capabilities.ForgeCapabilities;
import net.minecraftforge.items.SlotItemHandler;

/**
 * 蒸汽动力破碎机容器菜单
 */
public class SteamCrusherMenu extends AbstractContainerMenu {

    // 核心成员
    public final SteamPowerCrusherBlockEntity blockEntity;
    private final Level level;
    private final ContainerData data;

    // 槽位常量
    private static final int HOTBAR_SLOT_COUNT = 9;
    private static final int PLAYER_INVENTORY_ROW_COUNT = 3;
    private static final int PLAYER_INVENTORY_COLUMN_COUNT = 9;
    private static final int PLAYER_INVENTORY_SLOT_COUNT = PLAYER_INVENTORY_COLUMN_COUNT * PLAYER_INVENTORY_ROW_COUNT;
    private static final int VANILLA_SLOT_COUNT = HOTBAR_SLOT_COUNT + PLAYER_INVENTORY_SLOT_COUNT;
    private static final int VANILLA_FIRST_SLOT_INDEX = 0;

    private static final int TE_INVENTORY_SLOT_COUNT = 6; // 2 燃料 + 2输入 + 2输出
    private static final int TOTAL_SLOT_COUNT = VANILLA_SLOT_COUNT + TE_INVENTORY_SLOT_COUNT; // 36 + 6 = 42

    // 数据索引 - 更新为正确的数量
    public static final int DATA_PROGRESS = 0;
    public static final int DATA_MAX_PROGRESS = 1;
    public static final int DATA_HAS_RECIPE = 2;
    public static final int DATA_BATCH_SIZE = 3;
    public static final int DATA_TORQUE = 4;
    public static final int DATA_STAGE = 5;
    public static final int DATA_WATER_LEVEL = 6;
    public static final int DATA_FUEL_LEVEL = 7;
    public static final int DATA_IS_ACTIVE = 8;
    public static final int DATA_WATER_TANK1_AMOUNT = 9;
    public static final int DATA_WATER_TANK1_CAPACITY = 10;
    public static final int DATA_WATER_TANK2_AMOUNT = 11;
    public static final int DATA_WATER_TANK2_CAPACITY = 12;

    // 数据字段总数 - 使用动态计算而不是硬编码
    public final int DATA_COUNT;

    // ================ 构造函数 ================
    public SteamCrusherMenu(int containerId, Inventory inv, FriendlyByteBuf extraData) {
        this(
                containerId,
                inv,
                inv.player.level().getBlockEntity(extraData.readBlockPos()),
                // 使用动态数据字段数量
                new SimpleContainerData(inv.player.level().getBlockEntity(extraData.readBlockPos()) instanceof SteamPowerCrusherBlockEntity crusher ?
                        crusher.getDataFieldCount() : 13) // 默认值
        );
    }

    public SteamCrusherMenu(int containerId, Inventory inv, BlockEntity entity, ContainerData data) {
        super(MenuTypes.STEAM_CRUSHER_MENU.get(), containerId);
        checkContainerSize(inv, TE_INVENTORY_SLOT_COUNT);

        blockEntity = (SteamPowerCrusherBlockEntity) entity;
        this.level = inv.player.level();
        this.data = data;
        this.DATA_COUNT = data.getCount(); // 使用实际的数据字段数量



        addPlayerInventory(inv);
        addPlayerHotBar(inv);

        if (blockEntity != null) {
            this.blockEntity.getCapability(ForgeCapabilities.ITEM_HANDLER).ifPresent(handler -> {
                // 燃料槽位 (0-1)
                this.addSlot(new SlotItemHandler(handler, 0, 7, 62));
                this.addSlot(new SlotItemHandler(handler, 1, 27, 62));

                // 输入槽位 (2-3)
                this.addSlot(new SlotItemHandler(handler, 2, 59, 12));  // 右上输入
                this.addSlot(new SlotItemHandler(handler, 3, 59, 54));  // 右下输入

                // 输出槽位 (4-5)
                this.addSlot(new SlotItemHandler(handler, 4, 115, 34)); // 右上输出
                this.addSlot(new SlotItemHandler(handler, 5, 138, 56));  // 右下输出
            });
        }

        addDataSlots(data);
    }

    // ================ 快速移动物品 ================
    @Override
    public ItemStack quickMoveStack(Player player, int index) {
        ItemStack itemstack = ItemStack.EMPTY;
        Slot slot = this.slots.get(index);

        if (slot != null && slot.hasItem()) {
            ItemStack itemstack1 = slot.getItem();
            itemstack = itemstack1.copy();

            // 确定槽位类型
            if (index < VANILLA_SLOT_COUNT) {
                // 从玩家物品栏转移到机器
                if (!moveItemStackTo(itemstack1, VANILLA_SLOT_COUNT, TOTAL_SLOT_COUNT, false)) {
                    return ItemStack.EMPTY;
                }
            } else if (index < TOTAL_SLOT_COUNT) {
                // 从机器转移到玩家物品栏
                if (!moveItemStackTo(itemstack1, 0, VANILLA_SLOT_COUNT, false)) {
                    return ItemStack.EMPTY;
                }
            }

            if (itemstack1.isEmpty()) {
                slot.set(ItemStack.EMPTY);
            } else {
                slot.setChanged();
            }

            if (itemstack1.getCount() == itemstack.getCount()) {
                return ItemStack.EMPTY;
            }

            slot.onTake(player, itemstack1);
        }

        return itemstack;
    }

    // 辅助方法：检查物品是否为燃料
    private boolean isFuel(ItemStack stack) {
        return net.minecraftforge.common.ForgeHooks.getBurnTime(stack, null) > 0;
    }

    // ================ 容器验证 ================
    @Override
    public boolean stillValid(Player player) {
        return stillValid(
                ContainerLevelAccess.create(level, blockEntity.getBlockPos()),
                player,
                BlockLoader.STEAM_POWER_CRUSHER_MACHINE.get()
        );
    }

    // ================ 玩家物品栏添加 ================
    private void addPlayerInventory(Inventory playerInventory) {
        for (int row = 0; row < PLAYER_INVENTORY_ROW_COUNT; ++row) {
            for (int column = 0; column < PLAYER_INVENTORY_COLUMN_COUNT; ++column) {
                this.addSlot(
                        new Slot(
                                playerInventory,
                                column + row * 9 + 9,
                                7 + column * 18,
                                83 + row * 18
                        )
                );
            }
        }
    }

    private void addPlayerHotBar(Inventory playerInventory) {
        for (int i = 0; i < HOTBAR_SLOT_COUNT; ++i) {
            this.addSlot(
                    new Slot(
                            playerInventory,
                            i,
                            7 + i * 18,
                            141
                    )
            );
        }
    }

    // ================ 进度条数据 ================
    public int getProgress() {
        return DATA_PROGRESS < DATA_COUNT ? data.get(DATA_PROGRESS) : 0;
    }

    public int getMaxProgress() {
        return DATA_MAX_PROGRESS < DATA_COUNT ? data.get(DATA_MAX_PROGRESS) : 200;
    }

    public double getTorque() {
        return DATA_TORQUE < DATA_COUNT ? data.get(DATA_TORQUE) / 1000.0 : 0.0; // 还原为double
    }

    public StagedSteamMechanism.Stage getStage() {
        if (DATA_STAGE >= DATA_COUNT) {
            return StagedSteamMechanism.Stage.IDLE;
        }

        int stageIndex = data.get(DATA_STAGE);
        StagedSteamMechanism.Stage[] stages = StagedSteamMechanism.Stage.values();
        if (stageIndex >= 0 && stageIndex < stages.length) {
            return stages[stageIndex];
        }
        return StagedSteamMechanism.Stage.IDLE;
    }

    public int getWaterLevel() {
        return DATA_WATER_LEVEL < DATA_COUNT ? data.get(DATA_WATER_LEVEL) : 0;
    }

    public int getFuelLevel() {
        return DATA_FUEL_LEVEL < DATA_COUNT ? data.get(DATA_FUEL_LEVEL) : 0;
    }

    // 获取水槽1水位
    public int getWaterTank1Level() {
        return DATA_WATER_TANK1_AMOUNT < DATA_COUNT ? data.get(DATA_WATER_TANK1_AMOUNT) : 0;
    }

    // 获取水槽2水位
    public int getWaterTank2Level() {
        return DATA_WATER_TANK2_AMOUNT < DATA_COUNT ? data.get(DATA_WATER_TANK2_AMOUNT) : 0;
    }

    // 获取水槽1水位百分比
    public float getWaterTank1Percent() {
        int maxWater = SteamPowerCrusherBlockEntity.MAX_WATER_TANK_CAPACITY;
        int waterLevel = getWaterTank1Level();
        return maxWater > 0 ? (float) waterLevel / maxWater : 0f;
    }

    // 获取水槽2水位百分比
    public float getWaterTank2Percent() {
        int maxWater = SteamPowerCrusherBlockEntity.MAX_WATER_TANK_CAPACITY;
        int waterLevel = getWaterTank2Level();
        return maxWater > 0 ? (float) waterLevel / maxWater : 0f;
    }

    public boolean isWorking() {
        return DATA_PROGRESS < DATA_COUNT && data.get(DATA_PROGRESS) > 0;
    }

    /**
     * 获取配方进度百分比（0.0 - 1.0）
     */
    public float getProgressPercent() {
        int progress = this.getProgress();
        int maxProgress = this.getMaxProgress();
        if (maxProgress > 0 && progress > 0) {
            return (float) progress / maxProgress;
        }
        return 0f;
    }

    /**
     * 获取蒸汽压力百分比（0.0 - 1.0）
     */
    public float getSteamPressurePercent() {
        double maxTorque = SteamPowerCrusherBlockEntity.MAX_TORQUE;
        double currentTorque = getTorque();
        return maxTorque > 0 ? (float) (currentTorque / maxTorque) : 0f;
    }

    // ================ 辅助方法 ================

    /**
     * 检查数据索引是否有效
     * @param index 数据索引
     * @return 是否有效
     */
    private boolean isDataIndexValid(int index) {
        return index >= 0 && index < DATA_COUNT;
    }

    /**
     * 安全获取数据值
     * @param index 数据索引
     * @param defaultValue 默认值
     * @return 数据值
     */
    private int getDataSafe(int index, int defaultValue) {
        return isDataIndexValid(index) ? data.get(index) : defaultValue;
    }
}